package com.ithiema.luence;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;

public class LuencetestSearch {
    @Test
    public void testSearch() throws IOException, ParseException {
        //创建索引目录
        Directory directory = FSDirectory.open(new File("indexDir"));
        //索引读取对象
        IndexReader indexReader = DirectoryReader.open(directory);

        //索引搜索工具
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);

        // 创建查询解析器,两个参数：默认要查询的字段的名称，分词器
        QueryParser parser = new QueryParser("title", new IKAnalyzer());

        //创建查询对象
        Query query = parser.parse("加盟");

        //搜索数据，两个参数：查询条件对象，需要查询的最大结果数
        //返回结果 按照匹配度排名得分前N名的文档信息（包含查询到的总条数信息、所有符合条件的文档的编号信息）。
        TopDocs topDocs = indexSearcher.search(query, 1000);
        System.out.println(topDocs.totalHits);

        ScoreDoc[] docs = topDocs.scoreDocs;
        for (ScoreDoc doc : docs) {
            int docid = doc.doc;
            Document document = indexReader.document(docid);
            System.out.println("id:"+document.get("id"));
            System.out.println("title"+document.get("title"));
            System.out.println("得分:"+doc.score);
        }
    }
}
